package com.novel.config;


import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * redisson config 类
 *
 * @author huawei
 */
@Configuration
@ConditionalOnBean(RedissonProperties.class)
@EnableConfigurationProperties(RedissonProperties.class)
@ConditionalOnProperty(prefix = "com.ftf.tp.redis", value = "enable", havingValue = "true")
public class RedissonConfig {

    @Resource
    private RedissonProperties redissonProperties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "com.ftf.tp.redis", value = "enable", havingValue = "true")
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.setCodec(new JsonJacksonCodec());
        if (redissonProperties.getNodes() != null && redissonProperties.getNodes().length() > 10) {
            String[] nodes = redissonProperties.getNodes().split(",");
            List<String> newNodes = new ArrayList<>(nodes.length);
            Arrays.stream(nodes).forEach((index) -> newNodes.add(
                    index.startsWith("redis://") ? index : "redis://" + index));
            newNodes.toArray(nodes);
            config.useClusterServers()
                    .setScanInterval(2000)
                    .addNodeAddress(nodes)
                    .setPassword(redissonProperties.getPassword());
        } else {
            config.useSingleServer()
                    .setAddress("redis://" + redissonProperties.getAddress())
                    .setPassword(redissonProperties.getPassword())
                    .setDatabase(Integer.parseInt(redissonProperties.getDatabase()));
        }
        return Redisson.create(config);
    }


    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "com.ftf.tp.redis", value = "enable", havingValue = "true")
    public RedissonHelper redissonHelper() {
        return new RedissonHelper();
    }
}

